package com.limanyik.family.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.limanyik.family.common.entity.BasisUser;
import com.limanyik.family.common.entity.server.base.dto.MobilePhoneMessageDto;
import com.limanyik.family.common.entity.server.base.vo.MobilePhoneMessageVo;
import com.limanyik.family.common.entity.server.security.RegisterVo;
import com.limanyik.family.common.entity.server.security.VerificationCode;
import com.limanyik.family.common.enums.message.MessageInterface;
import com.limanyik.family.common.feign.MessageServiceApi;
import com.limanyik.family.common.respcode.ResponseErrorCode;
import com.limanyik.family.common.utils.*;
import com.limanyik.family.security.mapper.BasisUserMapper;
import com.limanyik.family.security.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    MessageServiceApi messageServiceApi;

    @Autowired
    BasisUserMapper basisUserMapper;

    /**
     * 默认缓存3分钟
     */
    @Value("${my-redis.register-cache-code}")
    private String registerCacheCodeTime;

    @Override
    public FamilyHttpResponse doRegister(RegisterVo registerVo) {
        // 生成伪随机
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setBusinessCode(MessageInterface.RegisterMessageEnum.VERIFICATION_CODE.getCode().toString());
        FamilyHttpRequest<MobilePhoneMessageVo> requestVo = new FamilyHttpRequest<>();
        String cacheKey = registerVo.getIsPhoneVerify() ? registerVo.getPhone() : registerVo.getEmail() + "_" + MessageInterface.RegisterMessageEnum.VERIFICATION_CODE.getCode();
        // 手机校验
        if (registerVo.getIsPhoneVerify()) {
            // 判断验证码是否存在
            if (redisUtil.isExistKey(cacheKey)) {
                return FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10000, "当前手机已发送验证码，请留意手机");
            }
            String verifyCode = RandomUtil.getRandomStringInRange(100000, 999999);
            verificationCode.setCode(verifyCode);
            requestVo.setData(new MobilePhoneMessageVo().setPhone(registerVo.getPhone()).setMessage(verifyCode));
            FamilyHttpResponse<MobilePhoneMessageDto> messageDto = messageServiceApi.sendMessage(requestVo);
            if (messageDto.getCode() == 500) {
                return FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10001, "短信验证码请求失败");
            }
        }
        verificationCode.setRequestTime(LocalDateTime.now());
        verificationCode.setSetPastDueTime(true);
        verificationCode.setPastDueTimeValue(Integer.parseInt(registerCacheCodeTime));
        verificationCode.setPastDueTimeUnit(TimeUnit.SECONDS);
        // 缓存验证对象
        if (!redisUtil.setValue(cacheKey, verificationCode)) {
            return FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10005, "缓存验证对象失败", "system");
        }
        // 设置过期时间（180秒）
        if (verificationCode.isSetPastDueTime()) {
            redisUtil.setPastDueTimeKey(cacheKey, verificationCode.getPastDueTimeValue(), verificationCode.getPastDueTimeUnit());
        }
        return FamilyHttpResponse.success();
    }

    @Override
    public FamilyHttpResponse doVerifyCode(RegisterVo registerVo) {
        String cacheKey = registerVo.getIsPhoneVerify() ? registerVo.getPhone() : registerVo.getEmail() + "_" + MessageInterface.RegisterMessageEnum.VERIFICATION_CODE.getCode();
        VerificationCode verificationCode = JSONObject.parseObject(redisUtil.getStringValue(cacheKey), VerificationCode.class);
        if (null == verificationCode) {
            return FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10002, "验证码不存在或已过期，请重新请求");
        }
        if (!registerVo.getCode().equals(verificationCode.getCode())) {
            return FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10003, "验证码不匹配");
        }
        // 添加用户
        BasisUser basisUser = new BasisUser();
        basisUser.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
        // 默认为游客
        basisUser.setNickName("游客" + RandomUtil.getRandomStringInRange(100000, 999999));
        basisUser.setAccount(registerVo.getIsPhoneVerify() ? registerVo.getPhone() : registerVo.getEmail());
        basisUser.setAge(18);
        basisUser.setEmailAddress(!registerVo.getIsPhoneVerify() ? registerVo.getEmail() : "");
        basisUser.setDeleteStatus(0);
        basisUser.setIsNoSingleSignOn(false);
        // 设置默认密码，加密方式为MD5，默认密码为123456，默认手机号为账号和加密盐
        basisUser.setYourCurrentPassword(ShiroMD5Util.encryption("123456", basisUser.getMobilePhone()));
        basisUser.setAccountStatus(true);
        basisUser.setSex(0);
        basisUser.setVersion("1.0.0");
        basisUser.setSuggest("这个人很懒，什么也没有留下");
        int userSaveSqlRun = basisUserMapper.insert(basisUser);
        if (userSaveSqlRun > 0) {
            // 删除缓存
            if (!redisUtil.delCache(cacheKey)) {
                FamilyHttpResponse.error(ResponseErrorCode.REGISTER_10004, "删除缓存失败", "system");
            }
        }
        return FamilyHttpResponse.success();
    }
}
